<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="类号" prop="categoryId">
                <el-input
                        v-model="queryParams.categoryId"
                        placeholder="请输入类号"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="ISBN" prop="bookIsbn">
                <el-input
                        v-model="queryParams.bookIsbn"
                        placeholder="请输入ISBN"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="书名" prop="bookName">
                <el-input
                        v-model="queryParams.bookName"
                        placeholder="请输入书名"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="出版社" prop="bookPublisher">
                <el-input
                        v-model="queryParams.bookPublisher"
                        placeholder="请输入出版社"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="作者" prop="bookAuthor">
                <el-input
                        v-model="queryParams.bookAuthor"
                        placeholder="请输入作者"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="出版日期" prop="bookPublishingyear">
                <el-date-picker clearable
                                v-model="queryParams.bookPublishingyear"
                                type="date"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择出版日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="bookList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" align="center" prop="bookId" />
            <el-table-column label="类号" align="center" prop="categoryId" />
            <el-table-column label="ISBN" align="center" prop="bookIsbn" />
            <el-table-column label="书名" align="center" prop="bookName" >
            <template #default="scope">
                <router-link :to="'/book-information/index/' + scope.row.bookId + '/' + scope.row.bookIsbn" class="link-type">
                    <span>{{ scope.row.bookName }}</span>
                </router-link>
            </template>
            </el-table-column>
            <el-table-column label="出版社" align="center" prop="bookPublisher" />
            <el-table-column label="作者" align="center" prop="bookAuthor" />
            <el-table-column label="出版日期" align="center" prop="bookPublishingyear" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.bookPublishingyear, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="库存" align="center" prop="bookInventory" />
            <el-table-column label="查看详情" align="center">
                <template #default="scope">
                    <el-button type="text" @click="viewDetails(scope.row)">查看详情</el-button>                </template>
            </el-table-column>
        </el-table>

        <div class="dialog-vertical">
            <el-dialog v-model="detailVisible" title="书籍详情" width="40%" class="dialog-vertical">
                <div v-if="currentBook" >
                    <el-row>
                        <el-col :span="2"></el-col>
                        <el-col :span="20">
                            <img v-if="currentBook.picture" :src="currentBook.picture" alt="Cover Image" class="book-cover" />
                        </el-col>
                        <el-col :span="2"></el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="2"></el-col>
                        <el-col :span="20">
                            <div v-if="currentBook.information">简介：{{ currentBook.information }}</div>
                        </el-col>
                        <el-col :span="2"></el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="2"></el-col>
                        <el-col :span="10">
                            <div>类别：{{ currentBook.categoryId }}</div>
                        </el-col>
                        <el-col :span="10">
                            <div>ISBN：{{ currentBook.bookIsbn }}</div>
                        </el-col>
                        <el-col :span="2"></el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="2"></el-col>
                        <el-col :span="10">
                            <div>书名：{{ currentBook.bookName }}</div>
                        </el-col>
                        <el-col :span="10">
                            <div>出版社：{{ currentBook.bookPublisher }}</div>
                        </el-col>
                        <el-col :span="2"></el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="2"></el-col>
                        <el-col :span="10">
                            <div>作者：{{ currentBook.bookAuthor }}</div>
                        </el-col>
                        <el-col :span="10">
                            <div>出版日期：{{ parseTime(currentBook.bookPublishingyear, '{y}-{m}-{d}') }}</div>
                        </el-col>
                        <el-col :span="2"></el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="2"></el-col>
                        <el-col :span="10">
                            <div>库存：{{ currentBook.bookInventory }}</div>
                        </el-col>
<!--                        <el-col :span="10">-->
<!--                            &lt;!&ndash; 预约按钮 &ndash;&gt;-->
<!--                            <div  class="button-container">-->
<!--                                <el-button type="primary" @click="handleReserve">预约</el-button>-->
<!--                            </div>-->
<!--                        </el-col>-->
                        <el-col :span="2"></el-col>
                    </el-row>

                </div>
            </el-dialog>
        </div>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改图书对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="bookRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="类号" prop="categoryId">
                    <el-input v-model="form.categoryId" placeholder="请输入类号" />
                </el-form-item>
                <el-form-item label="ISBN" prop="bookIsbn">
                    <el-input v-model="form.bookIsbn" placeholder="请输入ISBN" />
                </el-form-item>
                <el-form-item label="书名" prop="bookName">
                    <el-input v-model="form.bookName" placeholder="请输入书名" />
                </el-form-item>
                <el-form-item label="出版社" prop="bookPublisher">
                    <el-input v-model="form.bookPublisher" placeholder="请输入出版社" />
                </el-form-item>
                <el-form-item label="作者" prop="bookAuthor">
                    <el-input v-model="form.bookAuthor" placeholder="请输入作者" />
                </el-form-item>
                <el-form-item label="出版日期" prop="bookPublishingyear">
                    <el-date-picker clearable
                                    v-model="form.bookPublishingyear"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    placeholder="请选择出版日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="库存" prop="bookInventory">
                    <el-input v-model="form.bookInventory" placeholder="请输入库存" />
                </el-form-item>
                <el-form-item label="价格" prop="bookPrice">
                    <el-input v-model="form.bookPrice" placeholder="请输入价格" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Book">
import { listBook, getBook, delBook, addBook, updateBook } from "@/api/book/book";
import {parseTime} from "../../../utils/ruoyi.js";
import { getInformationByISBN } from "@/api/information/information.js";

const { proxy } = getCurrentInstance();
const detailVisible = ref(false); // 控制详情弹窗的显示
const currentBook = ref({}); // 当前显示的书籍详情
watch(currentBook, (newValue) => {
    console.log('Current Book Updated:', newValue);
});


const bookList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        bookIsbn: null,
        bookName: null,
        bookPublisher: null,
        bookAuthor: null,
        bookPublishingyear: null,
        bookInventory: null,
        bookPrice: null,
    },
    rules: {
        categoryId: [
            { required: true, message: "类号不能为空", trigger: "blur" }
        ],
        bookIsbn: [
            { required: true, message: "ISBN不能为空", trigger: "blur" }
        ],
        bookName: [
            { required: true, message: "书名不能为空", trigger: "blur" }
        ],
        bookPublisher: [
            { required: true, message: "出版社不能为空", trigger: "blur" }
        ],
        bookAuthor: [
            { required: true, message: "作者不能为空", trigger: "blur" }
        ],
        bookPublishingyear: [
            { required: true, message: "出版日期不能为空", trigger: "blur" }
        ],
        bookInventory: [
            { required: true, message: "库存不能为空", trigger: "blur" }
        ],
        bookPrice: [
            { required: true, message: "价格不能为空", trigger: "blur" }
        ]
    }
});

const { queryParams, form, rules } = toRefs(data);

// 查看详情的方法
// async function viewDetails(book) {
//     currentBook.value = book;
//     getInformationByISBN(book.bookIsbn).then(response => {
//         currentBook.value.information = response.information;
//         currentBook.value.picture = response.picture;
//         console.info(currentBook.value)
//     })
//     detailVisible.value = true;
// }

// 查看详情的方法
async function viewDetails(book) {
    currentBook.value = book;
    try {
        // 等待异步请求完成
        const response = await getInformationByISBN(book.bookIsbn);
        // 检查响应数据是否存在
        if (response && response.information && response.picture) {
            // 更新currentBook的信息
            currentBook.value.information = response.information;
            currentBook.value.picture = response.picture;
        } else {
            // 处理响应数据不完整的情况
            console.error('响应数据不完整');
            // 可能需要设置一个错误状态或者提示用户
        }
    } catch (error) {
        // 捕获并处理请求过程中的错误
        console.error('获取书籍信息失败:', error);
        // 可能需要设置一个错误状态或者提示用户
    }
    // 确保信息加载完成后再显示弹窗
    detailVisible.value = true;
}


/** 查询图书列表 */
function getList() {
    loading.value = true;
    listBook(queryParams.value).then(response => {
        bookList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        bookId: null,
        categoryId: null,
        bookIsbn: null,
        bookName: null,
        bookPublisher: null,
        bookAuthor: null,
        bookPublishingyear: null,
        bookInventory: null,
        bookPrice: null
    };
    proxy.resetForm("bookRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.bookId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加图书";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _bookId = row.bookId || ids.value
    getBook(_bookId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改图书";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["bookRef"].validate(valid => {
        if (valid) {
            if (form.value.bookId != null) {
                updateBook(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addBook(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _bookIds = row.bookId || ids.value;
    proxy.$modal.confirm('是否确认删除图书编号为"' + _bookIds + '"的数据项？').then(function() {
        return delBook(_bookIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('book/book/export', {
        ...queryParams.value
    }, `book_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style scoped>
.book-cover {
    width: 100px; /* 或者你想要的尺寸 */
    height: auto;
}
.button-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100px; /* 或者你需要的高度 */
}
/*.info {*/
/*    position: relative;*/
/*    height: 100vh;*/
/*}*/

.dialog-vertical { display: flex; padding: 20px; .el-dialog { margin: auto !important; } }

/*!*.centered-dialog {*!*/
/*!*    position: absolute;*!*/
/*!*    top: 50%;*!*/
/*!*    left: 50%;*!*/
/*!*    transform: translate(-50%, -50%);*!*/
/*!*    width: 50%; !* 或者您希望的宽度 *!*!*/
/*!*}*!*/
/*.centered-dialog { display: flex; justify-content: center; align-items: center; }*/
</style>
